package com.ruoyi.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.finance.domain.*;
import com.ruoyi.finance.domain.DTO.CheckOutDTO;
import com.ruoyi.finance.domain.DTO.KltPurchaseDetailStockDTO;
import com.ruoyi.finance.domain.VO.CheckOutVO;
import com.ruoyi.finance.domain.VO.KltInvoicingDTO;
import com.ruoyi.finance.domain.VO.PurchaseArrivedVO;
import com.ruoyi.finance.domain.VO.StockVO;
import com.ruoyi.finance.mapper.*;
import com.ruoyi.finance.service.KltPaymentRecordService;
import com.ruoyi.finance.service.KltPaymentSalesService;
import com.ruoyi.finance.service.KltPurchaseDetailService;
import com.ruoyi.finance.service.KltStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.*;

/**
 * (KltPurchaseDetail)表服务实现类
 *
 * @author makejava
 * @since 2024-12-19 12:18:03
 */
@Service("kltPurchaseDetailService")
@Transactional
public class KltPurchaseDetailServiceImpl extends ServiceImpl<KltPurchaseDetailDao, KltPurchaseDetail> implements KltPurchaseDetailService {

    @Resource
    private KltPurchaseDetailDao kltPurchaseDetailDao;
    @Resource
    private KltStockDao kltStockDao;
    @Autowired
    private PurchaseRecordsDao purchaseRecordsDao;
    @Autowired
    private KltPurchaseBatchDao kltPurchaseBatchDao;
    @Autowired
    private KltPaymentSalesService kltPaymentSalesService;
    @Autowired
    private KltStockService kltStockService;
    @Autowired
    private KltInvoicingDao kltInvoicingDao;

    @Override
    public List<KltPurchaseDetail> getAllKltPurchaseDetail(Wrapper<KltPurchaseDetail> kltPurchaseDetail) {
        List<KltPurchaseDetail> kltPurchaseDetaillist = kltPurchaseDetailDao.selectList(kltPurchaseDetail);
        return  kltPurchaseDetaillist;
    }


    @Override
    public List<KltPurchaseDetailStockDTO> getAllKltPurchaseDetailStockList(KltPurchaseDetailStockDTO kltPurchaseDetail) {

        List<KltPurchaseDetailStockDTO> allKltPurchaseDetailStockList = kltPurchaseDetailDao.getAllKltPurchaseDetailStockList(kltPurchaseDetail);

        return allKltPurchaseDetailStockList;
    }


    @Override
    public Boolean purchaseDetailInsertStock(KltPurchaseDetail kltPurchaseDetail ) {

        try {
            KltPurchaseDetail kltPurchaseDetail1 = kltPurchaseDetailDao.selectById(kltPurchaseDetail.getPurchaseDetailId());
            kltPurchaseDetail1.setIsArrived("2");
            int i1 = kltPurchaseDetailDao.updateById(kltPurchaseDetail1);
            KltStock kltStock = kltStockDao.selectById(kltPurchaseDetail.getStockId());
            kltStock.setStockQuantity(kltPurchaseDetail1.getQuantity()+kltStock.getStockQuantity());
            int i = kltStockDao.updateById(kltStock);


//            如果所有都到货后，更改为已到货未付款
//            如果已付款      更改为已结束

            KltPurchaseDetailStockDTO kltPurchaseDetailStockDTO = new KltPurchaseDetailStockDTO();
            kltPurchaseDetailStockDTO.setPurchaseId(String.valueOf(kltPurchaseDetail.getPurchaseId()));
            List<KltPurchaseDetailStockDTO> allKltPurchaseDetailStockList = kltPurchaseDetailDao.getAllKltPurchaseDetailStockList(kltPurchaseDetailStockDTO);
            for (KltPurchaseDetailStockDTO purchaseDetailStockDTO : allKltPurchaseDetailStockList) {
                if(!Objects.equals(purchaseDetailStockDTO.getIsArrived(), "2")){
                    KltPurchaseBatch kltPurchaseBatch = kltPurchaseBatchDao.selectById(kltPurchaseDetail.getPurchaseId());
                    if(Objects.equals(kltPurchaseBatch.getPurchaseType(), "0")){
                        kltPurchaseBatch.setPurchaseType("2");
                    }
                    else if(Objects.equals(kltPurchaseBatch.getPurchaseType(), "1")){
                        kltPurchaseBatch.setPurchaseType("3");
                    }
                    else if(Objects.equals(kltPurchaseBatch.getPurchaseType(), "2")){
                        kltPurchaseBatch.setPurchaseType("3");
                    }
                }else {
                    if(i1>0&&i>0){
                        return true;
                    }else {
                        throw new RuntimeException("库存更新失败");
                    }

                }
            }

            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Boolean purchaseDetailDeleteStock(List<Long> idList)  {
//        减库存
        for (int i = 0; i < idList.size(); i++) {
            KltPurchaseBatch kltPurchaseBatch = new KltPurchaseBatch();
            kltPurchaseBatch.setPurchaseId(Math.toIntExact(idList.get(i)));
            KltPurchaseDetail kltPurchaseDetail = kltPurchaseDetailDao.selectById(idList.get(i));

            KltStock kltStock = kltStockDao.selectById(kltPurchaseDetail.getStockId());
            kltStock.setStockQuantity(kltStock.getStockQuantity()-kltPurchaseDetail.getQuantity());

            int updated = kltStockDao.updateById(kltStock);
            if(updated==0){

                    throw new RuntimeException("库存还原失败");
            }
        }
        Boolean b = kltPurchaseDetailDao.updateDeleteKltPurchaseDetail(idList);
        return b;
    }


    @Override
    public List<PurchaseArrivedVO> purchaseDetailArrive(KltSalesOrder kltSalesOrder) {
//      展示合同到货情况
//      根据合同id获取所有批次
//        kltPurchaseDetailDao.getSalesAboutPurchaseArrive(kltSalesOrder.getSalesOrderId());
////      展示批次到货情况
//
//
//        List<PurchaseArrivedVO>  PurchaseArrivedVOList = new ArrayList<>();
//        PurchaseArrivedVO purchaseArrivedVO = new PurchaseArrivedVO();
//        purchaseArrivedVO .setProductName();
//
//        PurchaseArrivedVOList.add(purchaseArrivedVO);


        return null;
    }


    @Override
    public Map<String, Double> getProcurementStatistics(Integer salesOrderId) {
        List<StockVO> stockByOrderIdAndDetail = kltStockService.getStockByOrderIdAndDetailArrive(salesOrderId);
        List<KltInvoicingDTO> kltInvoicingDTOS = kltInvoicingDao.selectAmountByStockId(salesOrderId);
        for (KltInvoicingDTO kltInvoicingDTO : kltInvoicingDTOS) {
            stockByOrderIdAndDetail.forEach(stockVO -> {
                if(stockVO.getStockId().equals(kltInvoicingDTO.getStockId().toString())){
                    stockVO.setInvoiceAmount(kltInvoicingDTO.getAmountSum());
                }
            });
        }

//
        Double PurchaseAmount = 0D;
        Double OrderAmount = 0D;
        Double deliverAmount = 0D;
        Double invoiceAmount = 0D;


        for (StockVO stockVO : stockByOrderIdAndDetail) {
            PurchaseAmount += stockVO.getPurchaseAmount();
            OrderAmount += stockVO.getOrderAmount();
            deliverAmount += stockVO.getDeliverAmount();
            invoiceAmount += stockVO.getInvoiceAmount();
        }
        Map<String, Double> stringDoubleMap = new HashMap<>();
        stringDoubleMap.put("已采购",(PurchaseAmount));
        stringDoubleMap.put("未采购",(OrderAmount-PurchaseAmount<0?0:OrderAmount-PurchaseAmount));
        stringDoubleMap.put("已到货", Double.valueOf(kltPurchaseDetailDao.getPurchaserAndIsArrivedCount(salesOrderId)));

        stringDoubleMap.put("已发货",(deliverAmount));
        stringDoubleMap.put("未发货",(OrderAmount-deliverAmount<0?0:OrderAmount-deliverAmount));

        stringDoubleMap.put("已开票",(invoiceAmount));
        stringDoubleMap.put("未开票",(OrderAmount-invoiceAmount<0?0:OrderAmount-invoiceAmount));
        return stringDoubleMap;
    }
}

